/**
 * @param {string[]} cpdomains
 * @return {string[]}
 */
var subdomainVisits = function (cpdomains) {
  let domainMap = {};
  cpdomains.forEach(domain => {
    let info = domain.split(' ');
    let count = info[0];
    let url = info[1];
    url.split(/\./).reduceRight((prev, next) => {
      let key = next + (prev ? '.'+ prev : '');
      if(domainMap[key]) {
        domainMap[key] += Number(count);
      } else {
        domainMap[key] = Number(count);
      }
      return next + (prev ? '.'+ prev : '');
    }, '')
  })
  let keys = Object.keys(domainMap);
  let result = [];
  keys.forEach(key => {
    let value = domainMap[key];
    result.push(`${value} ${key}`);
  })
  return result;
};

// subdomainVisits(["9001 discuss.leetcode.com"]);
subdomainVisits(["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]);